package cn.itcast.bos.web.action.base;


import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {

    private Courier courier = new Courier();

    @Override
    public Courier getModel() {
        return courier;
    }

    @Autowired
    private CourierService courierService;

    @Action(value = "courier_save",results = {@Result(name = "success",location = "./pages/base/courier.html",type = "redirect")})
    public String save(){
        courierService.save(courier);
        return SUCCESS;
    }

    //接受浏览器传递过来的page和rows

    private Integer page;    //当前页
    private Integer rows;   //每页显示的数量

    public void setPage(Integer page) {
        this.page = page;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
    //有条件的分组查询

    @Action(value = "courier_pageQuery",results = {@Result(name = "success",
            type = "json"),
                @Result(name = "input",location = "/index.html")})
    public String pageQuery(){
        /*
        Pageable pageable = new PageRequest(page-1,rows);
        Page<Courier> pageData = courierService.findPageData(pageable);
        //将数据对象转化成jsson让页面中的datagrid识别
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("total",pageData.getTotalElements());//获取要显示的总数
        result.put("rows",pageData.getContent());//获取每页的内容
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS; 无条件的查询
        */
        //封装pagebale对象

        Pageable pageable = new PageRequest(page-1,rows);
        //创建Specification封装条件对象
       Specification<Courier> specification = new Specification<Courier>() {
           @Override
           public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               //创建一个list集合存放查询条件
               List<Predicate> list = new ArrayList<Predicate>();
               //条件一.couriernum相等
               if (StringUtils.isNotBlank(courier.getCourierNum())) {
                   Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
                   list.add(p1);

               }
               //模糊查询公司
               if (StringUtils.isNotBlank(courier.getCompany())) {
                   Predicate p2 = cb.like(root.get("company").as(String.class), "%" + courier.getCompany() + "%");
                   list.add(p2);
               }
               //查询类型
               if (StringUtils.isNotBlank(courier.getType())) {
                   Predicate p3 = cb.equal(root.get("type").as(String.class), courier.getType());
                    list.add(p3);
               }
               //第四个难,查询收派标准,牵涉到两个表standard和courier
               //join(标中字段名,和两个表的连接关系默认内连接)
               Join<Object, Object> standardJoin = root.join("standard", JoinType.INNER);
               if (courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())) {
                   Predicate p4 = cb.like(standardJoin.get("name").as(String.class), "%" + courier.getStandard().getName() + "%");
                   list.add(p4);
               }
               return cb.and(list.toArray(new Predicate[0]));
           }
       };
        Page<Courier> pageData = courierService.findPageData(specification,pageable);

        //将数据分装成页面需要的json
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("total",pageData.getTotalElements());
        map.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(map);
        return SUCCESS;
    }

    //创建一个变量接受ids
    private String ids ;

    public void setIds(String ids) {
        this.ids = ids;
    }

    //批量删除,修改快递员的状态
    @Action(value = "courier_delBatch",results = {@Result(name = "success",location = "./pages/base/courier.html",type = "redirect"),
                @Result(name = "input",location = "/index.html")})
    public String delBatch(){
        String[] idArray = ids.split(",");
        courierService.delBatch(idArray);

        return SUCCESS;
    }

    //批量还原快递员信息
    @Action(value = "courier_restore",results = {@Result(name = "success",location = "./pages/base/courier.html",type = "redirect"),
                @Result(name = "input",location = "/index.html")})
    public String restoreBatch(){
        String[] idArray = ids.split(",");
        courierService.restoreBatch(idArray);
        return SUCCESS;
    }

    /**
     * 查询没有关联分区的快递员
     * @return
     */
    @Action(value = "courier_findnoassociation",results = {@Result(name = "success",type = "json"),
                @Result(name = "input",location = "/index.html",type = "redirect")})
    public String findNoassociation(){
        List<Courier> couriers = courierService.findNoassociation();
        ActionContext.getContext().getValueStack().push(couriers);
        return SUCCESS;
    }

}
